package com.xqh.study.springtxjms.config;

import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.connection.JmsTransactionManager;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.transaction.PlatformTransactionManager;

import javax.jms.ConnectionFactory;

/**
 * @ClassName JmsConfig
 * @Description 使用 JmsTransactionManager 进行事务管理
 * @Author xuqianghui
 * @Date 2020/1/1 19:12
 * @Version 1.0
 */
@Configuration
@EnableJms
public class JmsConfig {

    @Bean
    public PlatformTransactionManager transactionManager(ConnectionFactory cf) {
        return new JmsTransactionManager(cf);
    }

    @Bean
    JmsTemplate jmsTemplate(ConnectionFactory cf) {
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory(cf);
        return jmsTemplate;
    }

    @Bean
    JmsListenerContainerFactory<?> jmsFactory(ConnectionFactory cf,
                                              PlatformTransactionManager transactionManager,
                                              DefaultJmsListenerContainerFactoryConfigurer configurer) {
        DefaultJmsListenerContainerFactory jmsFactory = new DefaultJmsListenerContainerFactory();
        configurer.configure(jmsFactory, cf);
        jmsFactory.setReceiveTimeout(10000L);//设置 10秒 读取消息超时时间.
        jmsFactory.setCacheLevelName("CACHE_CONNECTION");//缓存 connection
        jmsFactory.setTransactionManager(transactionManager);
        return jmsFactory;

    }
}
